package com.sunwayworld.basemodule.rm.equipment.instrumentacqconfig.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.client.MongoDatabase;
import com.sunwayworld.baseline.framework.utils.AccessHelper;
import com.sunwayworld.baseline.framework.utils.LimsDynamicDsHelper;
import com.sunwayworld.baseline.framework.utils.MongoDBUtil;
import com.sunwayworld.baseline.framework.utils.SmbV23Utils;
import com.sunwayworld.basemodule.rm.equipment.instrumentacq.bean.AccessDataATMBean;
import com.sunwayworld.basemodule.rm.equipment.instrumentacq.bean.LimsInstrumentAcqThicknessBean;
import com.sunwayworld.basemodule.rm.equipment.instrumentacq.bean.LimsInstrumentAcqVolresBean;
import com.sunwayworld.basemodule.rm.equipment.instrumentacq.service.LimsInstrumentAcqThicknessService;
import com.sunwayworld.basemodule.rm.equipment.instrumentacq.service.LimsInstrumentAcqVolresService;
import com.sunwayworld.basemodule.rm.equipment.instrumentacqconfig.bean.LimsInstrumentAcqConfigBean;
import com.sunwayworld.basemodule.rm.equipment.instrumentacqconfig.dao.LimsInstrumentAcqConfigDao;
import com.sunwayworld.basemodule.rm.equipment.instrumentacqconfig.service.LimsInstrumentAcqConfigService;
import com.sunwayworld.basemodule.rm.equipment.instrumentacqresult.bean.LimsInstrumentAcqResultBean;
import com.sunwayworld.basemodule.rm.equipment.instrumentacqresult.service.LimsInstrumentAcqResultService;
import com.sunwayworld.framework.at.annotation.AuditTrailEntry;
import com.sunwayworld.framework.at.annotation.AuditTrailType;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.exception.InvalidDataException;
import com.sunwayworld.framework.restful.data.RestJsonWrapperBean;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import com.sunwayworld.framework.utils.*;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import java.io.*;
import java.nio.file.Files;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Repository
@GikamBean
public class LimsInstrumentAcqConfigServiceImpl implements LimsInstrumentAcqConfigService {
    private static final Logger logger = LogManager.getLogger(LimsInstrumentAcqConfigServiceImpl.class);

    @Autowired
    private LimsInstrumentAcqConfigDao limsInstrumentAcqConfigDao;

    @Autowired
    private LimsInstrumentAcqThicknessService thicknessService;

    @Autowired
    private LimsInstrumentAcqVolresService limsInstrumentAcqVolresService;

    @Autowired
    private LimsInstrumentAcqResultService limsInstrumentAcqResultService;

    @Override
    @SuppressWarnings("unchecked")
    public LimsInstrumentAcqConfigDao getDao() {
        return limsInstrumentAcqConfigDao;
    }

    private static ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 2, 10l, TimeUnit.SECONDS, new LinkedBlockingQueue<>(100));

    @Override
    @Transactional
    @AuditTrailEntry(AuditTrailType.INSERT)
    public Long insert(RestJsonWrapperBean jsonWrapper) {
        LimsInstrumentAcqConfigBean limsInstrumentAcqConfig = jsonWrapper.parseUnique(LimsInstrumentAcqConfigBean.class);
        limsInstrumentAcqConfig.setId(ApplicationContextHelper.getNextIdentity());
        getDao().insert(limsInstrumentAcqConfig);
        return limsInstrumentAcqConfig.getId();
    }

    @Override
    public String connect(RestJsonWrapperBean wrapper) {
        LimsInstrumentAcqConfigBean acqConfig = wrapper.parseUnique(LimsInstrumentAcqConfigBean.class);
        Map<String,Object> result = new HashMap<>();
        if ("document".equals(acqConfig.getAcqType()) || "accessDB".equals(acqConfig.getAcqType())) {
            String ip = acqConfig.getIp();
            String username = acqConfig.getUserName();
            String password = acqConfig.getPassword();
            if (StringUtils.isBlank(ip)) {
                throw new InvalidDataException("设备IP未输入！");
            }
            if (StringUtils.isBlank(username)) {
                throw new InvalidDataException("用户名未输入！");
            }
            if (StringUtils.isBlank(password)) {
                throw new InvalidDataException("密码未输入！");
            }
            Boolean isSuccess = SmbV23Utils.connect(ip, username, password);
            result.put("result", isSuccess);
        }else if("database".equals(acqConfig.getAcqType())){
            String username = acqConfig.getDbUserName();
            String password = acqConfig.getDbPassword();
            String url = acqConfig.getUrl();
            String driverClassName = acqConfig.getDriverClassName();
            LimsDynamicDsHelper dynamicDsHelper = LimsDynamicDsHelper.getInstance();
            JdbcTemplate jdbc = dynamicDsHelper.getJdbcTemplate(username, password, url, driverClassName);
            result.put("result", 1);
        } else {
            result.put("result", 0);
        }
        return JSONObject.toJSONString(result);
    }

    @Override
    public void instrumentAcqSchedule() {
        logger.info("仪器数据采集  开始！ beginTime:{}", LocalDateTime.now());
//        List<LimsInstrumentAcqResultBean> acqResultBeanList = new ArrayList<>();
        List<LimsInstrumentAcqConfigBean> acqConfigList = this.selectAll();

        PlatformTransactionManager transactionManager = ApplicationContextHelper.getBean(PlatformTransactionManager.class);
        logger.info("要采集的设备数量:{}",acqConfigList.size());
        for (LimsInstrumentAcqConfigBean acqConfig : acqConfigList){
            if (ObjectUtils.isEmpty(acqConfig.getInstrumentType())){
                continue;
            }
            if (ObjectUtils.isEmpty(acqConfig.getAcqType())){
                continue;
            }
            logger.info("仪器instrumentCode:{} 开始采集！", acqConfig.getInstrumentCode());
            // 1.文件采集方式
            // 2.access数据库采集方式
            // 3.数据库采集方式
            Thread run = new Thread(() -> {
                List<Map<String, Object>> fileMaps = new ArrayList<>();
                if ("document".equals(acqConfig.getAcqType())) {
                    //弃用，转到com.sunwayworld.basemodule.rm.equipment.equiptfileacq
                    /*if (ObjectUtils.isEmpty(acqConfig.getReadingMode())) {
                        return;
                    }
                    // 1.共享文件夹方式
                    if ("shareDocument".equals(acqConfig.getReadingMode())) {
                        fileMaps = gainFileFromShareDocument(acqConfig);
                        for (Map<String, Object> fileMap : fileMaps) {
                            String fileType = (String) fileMap.get("fileType");
                            if (fileType.indexOf("CSV") == 0) {
                                dealCsvFile(fileMap, transactionManager);
                            } else if (fileType.indexOf("XLS") == 0) {
                                dealXlsFile(fileMap, transactionManager);
                            } else if (fileType.indexOf("TXT") == 0) {
                                dealTxtFile(fileMap, transactionManager);
                            }
                        }
                    }*/
                } else if ("accessDB".equals(acqConfig.getAcqType())) {
                    //弃用，ATM采用接口采集com.sunwayworld.basemodule.rm.equipment.restful.impl.EquiptDataAcqResourceImpl.atmAcq
                    /*fileMaps = gainFileFromShareDocument(acqConfig);
                    for (Map<String, Object> fileMap : fileMaps) {
                        String fileType = (String) fileMap.get("fileType");
                        if (fileType.indexOf("MDB") == 0) {
                            dealAccessDBFile(fileMap, acqConfig, transactionManager);
                        }
                    }*/
                } else if ("database".equals(acqConfig.getAcqType())) {
                    // 1.sqlserver数据库
                    fileMaps = gainDataFromDB(acqConfig);
                    dealDBData(fileMaps);
                }
                TransactionStatus transactionExecuting1 = transactionManager.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW));
                try {
                    LimsInstrumentAcqResultBean resultBean = new LimsInstrumentAcqResultBean();
                    resultBean.setId(ApplicationContextHelper.getNextIdentity());
                    resultBean.setConfigId(acqConfig.getId());
                    resultBean.setCreatedTime(LocalDateTime.now());
                    resultBean.setInstrumentCode(acqConfig.getInstrumentCode());
                    resultBean.setInstrumentName(acqConfig.getInstrumentName());
                    resultBean.setAcqStatus("success");
                    limsInstrumentAcqResultService.getDao().insert(resultBean);
                    transactionManager.commit(transactionExecuting1);
                } catch (Exception e) {
                    logger.error("采集结果插入LIMS数据库失败!");
                    e.printStackTrace();
                    transactionManager.rollback(transactionExecuting1);
                }
                logger.info("仪器instrumentCode:{} 采集结束！", acqConfig.getInstrumentCode());
            });

            executor.submit(run);
        }
    }

    private List<Map<String, Object>> gainFileFromShareDocument(LimsInstrumentAcqConfigBean acqConfig) {
        logger.info("设备文件->本地  开始  instrumentCode:{}", acqConfig.getInstrumentCode());
        List<Map<String, Object>> fileMaps = new ArrayList<>();
        String ip = acqConfig.getIp();
        //ip没填返回空集合跳过
        if (StringUtils.isBlank(ip.trim())) return fileMaps;
        String username = acqConfig.getUserName();
        String password = acqConfig.getPassword();
        String rootUrl = acqConfig.getCollectionPath();
        String localPath = SystemUtils.getWorkingPath().resolve("files").resolve(acqConfig.getSavePath()).resolve(acqConfig.getId().toString()).toFile().getAbsolutePath();
        logger.info("ip:{} username:{} password:{} rootUrl:{} localPath:{}", ip, username, password, rootUrl, localPath);

        fileMaps = SmbV23Utils.gainFileFromSmb(rootUrl, localPath, ip, username, password);
        logger.info("设备文件->本地  结束  configId:{} instrumentCode:{} szie:{}", acqConfig.getId(), acqConfig.getInstrumentCode(), fileMaps.size());

        return fileMaps;
    }

    private List<Map<String, Object>> gainDataFromDB(LimsInstrumentAcqConfigBean acqConfig) {
        logger.info("设备数据->本地  开始  configId:{} instrumentCode:{}", acqConfig.getId(), acqConfig.getInstrumentCode());
        String username = acqConfig.getDbUserName();
        String password = acqConfig.getDbPassword();
        String url = acqConfig.getUrl();
        String driverClassName = acqConfig.getDriverClassName();
        String sql1 = "select * " +
                "from v_bt4560 " +
                "where testdate >= ? and testdate <= ? " +
                "order by testdate asc";
        LocalDate now = LocalDate.now();
        LocalDate lastDate = now.minusDays(1);
        LocalTime beginTime = LocalTime.of(0, 0, 0);
        LocalTime endTime = LocalTime.of(23, 59, 59);
        String begin = DateTimeUtils.formatLocalDateTime(LocalDateTime.of(lastDate, beginTime));
        String end = DateTimeUtils.formatLocalDateTime(LocalDateTime.of(lastDate, endTime));
        List<Map<String, Object>> dataMaps = new ArrayList<>();
        LimsDynamicDsHelper dynamicDsHelper = LimsDynamicDsHelper.getInstance();
        JdbcTemplate jdbc = dynamicDsHelper.getJdbcTemplate(username, password, url, driverClassName);
        dataMaps = dynamicDsHelper.queryForList(jdbc,sql1,begin,end);
        logger.info("设备数据->本地  结束  configId:{} instrumentCode:{}", acqConfig.getId(), acqConfig.getInstrumentCode());

        return dataMaps;
    }

    private void dealCsvFile(Map<String, Object> fileMap, PlatformTransactionManager transactionManager) {
        String type = (String) fileMap.get("type");
        File file = (File) fileMap.get("file");
        String encode = EncodingUtils.detect(file); //文件编码
        TransactionStatus transactionExecuting1 = transactionManager.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW));
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(Files.newInputStream(file.toPath()), encode))) {
            if (type.indexOf("SPEA1")==0) {
                List<LimsInstrumentAcqThicknessBean> thicknessBeanList = new ArrayList<>();
                LocalDateTime NOW = LocalDateTime.now();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    String[] cols = line.split(",");
                    if (StringUtils.isBlank(cols[0].trim()) || ObjectUtils.equals(cols[0], "Timestamp")) { //去除空列和表头
                        continue;
                    }

                    LimsInstrumentAcqThicknessBean thicknessBean = new LimsInstrumentAcqThicknessBean();
                    thicknessBean.setId(ApplicationContextHelper.getNextIdentity());
                    thicknessBean.setInstrumentType(type);
                    //测试时间
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                    sdf.setTimeZone(TimeZone.getTimeZone("PRC"));
                    Date date = sdf.parse(cols[0]);
                    Instant instant = date.toInstant();
                    ZoneId zoneId = ZoneId.systemDefault();
                    LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
                    thicknessBean.setTestTime(localDateTime);
                    thicknessBean.setMeasurementTime(cols[1]);
                    thicknessBean.setRecipeName(cols[2]);
                    thicknessBean.setFixtureId(cols[3]);
                    thicknessBean.setOrdNo(cols[4]);
                    thicknessBean.setTargetForce(cols[6]);
                    thicknessBean.setForce(cols[7]);
                    thicknessBean.setNominalThickness(cols[8]);
                    thicknessBean.setThickness(cols[9]);
                    thicknessBean.setParallelism(cols[10]);
                    thicknessBean.setAcqTime(NOW);
                    thicknessBeanList.add(thicknessBean);
                }
                thicknessService.getDao().insert(thicknessBeanList);
            } else if (type.indexOf("SPEA2")==0) {
                List<LimsInstrumentAcqVolresBean> volresBeanList = new ArrayList<>();
                LocalDateTime now = LocalDateTime.now();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    String[] cols = line.split(",");
                    if (StringUtils.isBlank(cols[0].trim()) || ObjectUtils.equals(cols[0], "Timestamp")) { //去除空列和表头
                        continue;
                    }

                    LimsInstrumentAcqVolresBean volresBean = new LimsInstrumentAcqVolresBean();
                    volresBean.setId(ApplicationContextHelper.getNextIdentity());
                    volresBean.setInstrumentType(type);
                    //测试时间
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                    sdf.setTimeZone(TimeZone.getTimeZone("PRC"));
                    Date date = sdf.parse(cols[0]);
                    Instant instant = date.toInstant();
                    ZoneId zoneId = ZoneId.systemDefault();
                    LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
                    volresBean.setTestTime(localDateTime);
                    volresBean.setMeasurementTime(cols[1]);
                    volresBean.setRecipeName(cols[2]);
                    volresBean.setOrdNo(cols[3]);
                    volresBean.setVoltage(cols[5]);
                    volresBean.setResistance(cols[6]);
                    volresBean.setFrequency(cols[7]);
                    volresBean.setAcqTime(now);
                    volresBeanList.add(volresBean);
                }
                limsInstrumentAcqVolresService.getDao().insert(volresBeanList);
            } else if (type.indexOf("YHD")==0) {
                List<LimsInstrumentAcqThicknessBean> thicknessBeanList = new ArrayList<>();
                LocalDateTime NOW = LocalDateTime.now();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    String[] cols = line.split("\t");
                    if (StringUtils.isBlank(cols[0].trim()) || ObjectUtils.equals(cols[0], "时间")) { //去除空列和表头
                        continue;
                    }

                    LimsInstrumentAcqThicknessBean thicknessBean = new LimsInstrumentAcqThicknessBean();
                    thicknessBean.setId(ApplicationContextHelper.getNextIdentity());
                    thicknessBean.setInstrumentType(type);
                    //测试时间
                    String dt = SmbV23Utils.fillDateStr(cols[0]); //转换一波
                    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    LocalDateTime localDateTime = LocalDateTime.parse(dt, df);
                    thicknessBean.setTestTime(localDateTime);
                    thicknessBean.setOrdNo(cols[1]);
                    thicknessBean.setThickness(cols[2]);
                    thicknessBean.setAcqTime(NOW);
                    thicknessBeanList.add(thicknessBean);
                }
                thicknessService.getDao().insert(thicknessBeanList);
            }
            transactionManager.commit(transactionExecuting1);
        } catch (IOException e) {
            logger.error("设备测试数据文件读取失败! type:{} filePath:{}", type, file.toPath());
            e.printStackTrace();
            transactionManager.rollback(transactionExecuting1);
        } catch (ParseException e) {
            logger.error("设备测试数据文件读取失败!时间转换异常! type:{} filePath: {}", type, file.toPath());
            e.printStackTrace();
            transactionManager.rollback(transactionExecuting1);
        }
    }

    private void dealXlsFile(Map<String, Object> fileMap, PlatformTransactionManager transactionManager) {
        String type = (String) fileMap.get("type");
        File file = (File) fileMap.get("file");
        TransactionStatus transactionExecuting1 = transactionManager.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW));
        if (type.indexOf("YHD")==0) {
            XSSFWorkbook workbook = null;
            InputStream fileInputStream = null;
            try {
                fileInputStream = Files.newInputStream(file.toPath());
                workbook = new XSSFWorkbook(fileInputStream);
                XSSFSheet sheet = workbook.getSheetAt(0);
                int rows = sheet.getPhysicalNumberOfRows();
                List<LimsInstrumentAcqThicknessBean> thicknessBeanList = new ArrayList<>();
                LocalDateTime NOW = LocalDateTime.now();
                for (int i = 0; i < rows; i++) {
                    //从0开始取每一行
                    XSSFRow rowData = sheet.getRow(i);
                    XSSFCell cellData0 = rowData.getCell(0);
                    if (ObjectUtils.isEmpty(cellData0.getStringCellValue().trim()) ||
                            ObjectUtils.equals(cellData0.getStringCellValue(), "时间")) { //去除空列和每个表头内容（可能多次出现）
                        continue;
                    }

                    LimsInstrumentAcqThicknessBean thicknessBean = new LimsInstrumentAcqThicknessBean();
                    thicknessBean.setId(ApplicationContextHelper.getNextIdentity());
                    thicknessBean.setInstrumentType(type);
                    //测试时间
                    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
                    LocalDateTime localDateTime = LocalDateTime.parse(cellData0.getStringCellValue(), df);
                    thicknessBean.setTestTime(localDateTime);
                    XSSFCell cellData1 = rowData.getCell(1);
                    thicknessBean.setOrdNo(cellData1.getStringCellValue());
                    XSSFCell cellData2 = rowData.getCell(2);
                    thicknessBean.setThickness(cellData2.getStringCellValue());
                    thicknessBean.setAcqTime(NOW);
                    thicknessBeanList.add(thicknessBean);
                }
                thicknessService.getDao().insert(thicknessBeanList);
                transactionManager.commit(transactionExecuting1);
            } catch (IOException e) {
                logger.error("设备测试数据文件读取失败! type:{} filePath:{}", type, file.toPath());
                e.printStackTrace();
                transactionManager.rollback(transactionExecuting1);
            } finally {
                try {
                    if (fileInputStream != null) {
                        fileInputStream.close();
                    }
                    if (workbook != null) {
                        workbook.close();
                    }
                } catch (Exception s) {
                    s.printStackTrace();
                }
            }
        }
    }

    private void dealTxtFile(Map<String, Object> fileMap, PlatformTransactionManager transactionManager) {
        String type = (String) fileMap.get("type");
        File file = (File) fileMap.get("file");
        String encode = EncodingUtils.detect(file); //文件编码
        TransactionStatus transactionExecuting1 = transactionManager.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW));
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(Files.newInputStream(file.toPath()), encode))) {
            if (type.indexOf("SPEA1")==0) {
                List<LimsInstrumentAcqThicknessBean> thicknessBeanList = new ArrayList<>();
                LocalDateTime NOW = LocalDateTime.now();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    String[] cols = line.split(",");
                    if (StringUtils.isBlank(cols[0].trim()) || ObjectUtils.equals(cols[0], "Timestamp")) { //去除空列和表头
                        continue;
                    }

                    LimsInstrumentAcqThicknessBean thicknessBean = new LimsInstrumentAcqThicknessBean();
                    thicknessBean.setId(ApplicationContextHelper.getNextIdentity());
                    thicknessBean.setInstrumentType(type);
                    //测试时间
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                    sdf.setTimeZone(TimeZone.getTimeZone("PRC"));
                    Date date = sdf.parse(cols[0]);
                    Instant instant = date.toInstant();
                    ZoneId zoneId = ZoneId.systemDefault();
                    LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
                    thicknessBean.setTestTime(localDateTime);
                    thicknessBean.setMeasurementTime(cols[1]);
                    thicknessBean.setRecipeName(cols[2]);
                    thicknessBean.setFixtureId(cols[3]);
                    thicknessBean.setOrdNo(cols[4]);
                    thicknessBean.setTargetForce(cols[6]);
                    thicknessBean.setForce(cols[7]);
                    thicknessBean.setNominalThickness(cols[8]);
                    thicknessBean.setThickness(cols[9]);
                    thicknessBean.setParallelism(cols[10]);
                    thicknessBean.setAcqTime(NOW);
                    thicknessBeanList.add(thicknessBean);
                }
                thicknessService.getDao().insert(thicknessBeanList);
            } else if (type.indexOf("SPEA2")==0) {
                List<LimsInstrumentAcqVolresBean> volresBeanList = new ArrayList<>();
                LocalDateTime now = LocalDateTime.now();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    String[] cols = line.split(",");
                    if (StringUtils.isBlank(cols[0].trim()) || ObjectUtils.equals(cols[0], "Timestamp")) { //去除空列和表头
                        continue;
                    }

                    LimsInstrumentAcqVolresBean volresBean = new LimsInstrumentAcqVolresBean();
                    volresBean.setId(ApplicationContextHelper.getNextIdentity());
                    volresBean.setInstrumentType(type);
                    //测试时间
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                    sdf.setTimeZone(TimeZone.getTimeZone("PRC"));
                    Date date = sdf.parse(cols[0]);
                    Instant instant = date.toInstant();
                    ZoneId zoneId = ZoneId.systemDefault();
                    LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
                    volresBean.setTestTime(localDateTime);
                    volresBean.setMeasurementTime(cols[1]);
                    volresBean.setRecipeName(cols[2]);
                    volresBean.setOrdNo(cols[3]);
                    volresBean.setVoltage(cols[5]);
                    volresBean.setResistance(cols[6]);
                    volresBean.setFrequency(cols[7]);
                    volresBean.setAcqTime(now);
                    volresBeanList.add(volresBean);
                }
                limsInstrumentAcqVolresService.getDao().insert(volresBeanList);
            } else if (type.indexOf("YHD")==0) {
                List<LimsInstrumentAcqThicknessBean> thicknessBeanList = new ArrayList<>();
                LocalDateTime NOW = LocalDateTime.now();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    String[] cols = line.split("\t");
                    if (StringUtils.isBlank(cols[0].trim()) || ObjectUtils.equals(cols[0], "时间")) { //去除空列和表头
                        continue;
                    }

                    LimsInstrumentAcqThicknessBean thicknessBean = new LimsInstrumentAcqThicknessBean();
                    thicknessBean.setId(ApplicationContextHelper.getNextIdentity());
                    thicknessBean.setInstrumentType(type);
                    //测试时间
                    String dt = SmbV23Utils.fillDateStr(cols[0]); //转换一波
                    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    LocalDateTime localDateTime = LocalDateTime.parse(dt, df);
                    thicknessBean.setTestTime(localDateTime);
                    thicknessBean.setOrdNo(cols[1]);
                    thicknessBean.setThickness(cols[2]);
                    thicknessBean.setAcqTime(NOW);
                    thicknessBeanList.add(thicknessBean);
                }
                thicknessService.getDao().insert(thicknessBeanList);
            }
            transactionManager.commit(transactionExecuting1);
        } catch (IOException e) {
            logger.error("设备测试数据文件读取失败! type:{} filePath:{}", type, file.toPath());
            e.printStackTrace();
            transactionManager.rollback(transactionExecuting1);
        } catch (ParseException e) {
            logger.error("设备测试数据文件读取失败!时间转换异常! type:{} filePath: {}", type, file.toPath());
            e.printStackTrace();
            transactionManager.rollback(transactionExecuting1);
        }
    }

    private void dealAccessDBFile(Map<String, Object> fileMap, LimsInstrumentAcqConfigBean acqConfig, PlatformTransactionManager transactionManager) {
        LocalDate now = LocalDate.now();
        String type = (String) fileMap.get("type");
        File file = (File) fileMap.get("file");
        TransactionStatus transactionExecuting1 = transactionManager.getTransaction(new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW));
        if (type.indexOf("ATM")==0) {
            try {
                //数据库地址
                String path = file.getAbsolutePath(); //文件全路径
                String user = acqConfig.getDbUserName(); //用户名
                String password = acqConfig.getDbPassword(); //密码
                AccessHelper accessHelper = new AccessHelper(path, user, password);
                //查询数据 昨天00:00:00-昨天23:59:59
                LocalDate lastDate = now.minusDays(1);
                LocalTime beginTime = LocalTime.of(0, 0, 0);
                LocalTime endTime = LocalTime.of(23, 59, 59);
                String begin = DateTimeUtils.formatLocalDateTime(LocalDateTime.of(lastDate, beginTime));
                String end = DateTimeUtils.formatLocalDateTime(LocalDateTime.of(lastDate, endTime));
                String a = "SELECT id, test_time, product_no, product_barcode, test_thickness, thickness_up, thickness_down, test_result FROM tbl_test_report where test_time >= '" + begin + "' and test_time <= '" + end + "'";
                String gbk = new String(a.getBytes("gbk"));
                List<AccessDataATMBean> accessResultList = accessHelper.executeQueryList(gbk, AccessDataATMBean.class);
                if (CollectionUtils.isEmpty(accessResultList)) {
                    return;
                }
                List<LimsInstrumentAcqThicknessBean> thicknessBeanList = new ArrayList<>();
                LocalDateTime NOW = LocalDateTime.now();
                for (AccessDataATMBean result : accessResultList) {
                    LimsInstrumentAcqThicknessBean thicknessBean = new LimsInstrumentAcqThicknessBean();
                    thicknessBean.setId(ApplicationContextHelper.getNextIdentity());
                    thicknessBean.setInstrumentType(type);
                    thicknessBean.setOrderNo(result.getId().toString());
                    thicknessBean.setTestTime(result.getTest_time());
                    thicknessBean.setPackageNo(result.getProduct_no());
                    thicknessBean.setOrdNo(result.getProduct_barcode());
                    thicknessBean.setThickness(result.getTest_thickness());
                    thicknessBean.setThicknessMaximum(result.getThickness_up());
                    thicknessBean.setThicknessMinimum(result.getThickness_down());
                    thicknessBean.setTestResult(result.getTest_result());
                    thicknessBean.setAcqTime(NOW);
                    thicknessBeanList.add(thicknessBean);
                }
                thicknessService.getDao().insert(thicknessBeanList);
                transactionManager.commit(transactionExecuting1);
            } catch (Exception e) {
                logger.error("access数据库读取失败! type:{} filePath:{}", type, file.toPath());
                e.printStackTrace();
                transactionManager.rollback(transactionExecuting1);
            }
        }
    }

    private void dealDBData(List<Map<String, Object>> dataMaps) {
        try {
            List<Document> volresBeanList = new ArrayList<>();
            LocalDateTime now = LocalDateTime.now();
            for (Map<String, Object> dataMap : dataMaps) {
                LimsInstrumentAcqVolresBean volresBean = new LimsInstrumentAcqVolresBean();
                volresBean.setId(ApplicationContextHelper.getNextIdentity());
                volresBean.setInstrumentType("BT4560");
                String testdate = ObjectUtils.toString(dataMap.get("testdate"));
                LocalDateTime testTime = null;
                if (!ObjectUtils.isEmpty(testdate.trim())) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
                    sdf.setTimeZone(TimeZone.getTimeZone("PRC"));
                    Date date = sdf.parse(testdate);
                    Instant instant = date.toInstant();
                    ZoneId zoneId = ZoneId.systemDefault();
                    testTime = instant.atZone(zoneId).toLocalDateTime();
                }
                volresBean.setTestTime(testTime);
                volresBean.setOrdNo(ObjectUtils.toString(dataMap.get("code")));
                volresBean.setVoltage(ObjectUtils.toString(dataMap.get("v")));
                volresBean.setResistance(ObjectUtils.toString(dataMap.get("R")));
                volresBean.setTemp(ObjectUtils.toString(dataMap.get("temp")));
                volresBean.setFrequency(ObjectUtils.toString(dataMap.get("Z")));
                volresBean.setAcqTime(now);
                String json = JSON.toJSONString(volresBean);
                Document document = Document.parse(json);
                volresBeanList.add(document);
            }
            MongoTemplate mongoTemplate = MongoDBUtil.getMongoTemplate("EPTACQ_SH");
            if (com.sunwayworld.framework.utils.ObjectUtils.isEmpty(mongoTemplate)) {
                logger.error("连接mongodb数据库失败，type:{}", "");
                return;
            }
            MongoDatabase eptacq = mongoTemplate.getDb();
            eptacq.getCollection("VOLRES").insertMany(volresBeanList);
        } catch (Exception e) {
            logger.error("数据插入MONGO失败!");
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        System.out.println(System.getProperty("user.dir"));
    }
}
